import { settleWeightArr } from '../settleWeightArr';

import { toStringTypeCheck } from '../../global';

let weightMap = {};

let enstartArr = [];

let endReslove = -2;

let uniSort = undefined;

let lastResult = [];

let lastWeightMap;

let targetObj;

function restartWeightBy() {
  lastWeightMap = weightMap;

  weightMap = {};

  enstartArr = [];

  endReslove = -2;

  uniSort = undefined;

  targetObj = undefined;
}

/**
 * 升序 排序 有字典的 数据 返回一个新的 根据数据字典权重 的升序数组
 * @param {pointer} target 目标 的 数据链接 (* 指针) -- [...keys]
 * @param {Object} weightDiction 目标 权重字典 --["weight"] (obj[key]["weight"]关键字)
 * @param {Function} uniFunc 最小单元 排序 uniFunc(args) return []
 * @returns
 */
function reorderbyWeight(target, weightDiction, uniFunc) {
  if (endReslove === -2) {
    endReslove = -1;
    targetObj = target;
    uniSort = uniFunc;
  }
  if (toStringTypeCheck(target, 'array') && target.length > 0) {
    reorderbyWeight(target[0], weightDiction);
    target.splice(0, 1);
    endReslove = target.length;
    reorderbyWeight(target, weightDiction);
  }

  if (toStringTypeCheck(target, 'string')) {
    try {
      let weight = tryGetKeyWeight(target, weightDiction);
      if (weight === false) {
        throw new Error(
          'We got an unexpected result can not get weight number value'
        );
      }
      settleWeightArr(enstartArr, weight);
    } catch (error) {
      console.error(error);
    }
  }
  if (endReslove === 0) {
    endReslove = false;
  }
  if (endReslove === false) {
    endReslove = true;
    lastResult = assembleWeightArr();
    // targetObj = lastResult;
    targetObj.splice(1, undefined, ...lastResult);
    // console.log(targetObj);
    //用完自己清理
    restartWeightBy();
  }
  return { lastResult, lastWeightMap };
}

function tryGetKeyWeight(key, weightDiction) {
  if (key == undefined || weightDiction == undefined) {
    return false;
  }
  if (weightDiction[key] == undefined) {
    return false;
  }
  if (weightDiction[key]['weight'] == undefined) {
    return false;
  }
  weightMap[key] = weightDiction[key]['weight']
    ? Number(weightDiction[key]['weight'])
    : -1;
  return weightMap[key];
}

function assembleWeightArr() {
  let gatherByweight = [];
  for (let index = 0; index < enstartArr.length; index++) {
    let arr = toGetWeightKey(enstartArr[index]);
    if (uniSort != undefined) {
      arr = uniSort(arr);
    }
    gatherByweight.push(...arr);
  }
  return gatherByweight;
}

function toGetWeightKey(weight) {
  let getArr = [];
  for (const key in weightMap) {
    if (Object.hasOwnProperty.call(weightMap, key)) {
      if (weightMap[key] == weight) {
        getArr.push(key);
      }
    }
  }
  return getArr;
}

export { reorderbyWeight };
